package mk.jug.academy.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import mk.jug.academy.model.Comment;
import mk.jug.academy.model.CommentStatus;
import mk.jug.academy.model.Page;

import org.springframework.stereotype.Repository;


/**
 * DAO for the {@link Comment} entity model.
 *
 * @author Ice.Penov
 */
@Repository
public class CommentDAO extends GenericDAO<Comment> {
	
	/**
	 * Returns the {@link Comment}s for the given content ID, ordered by
	 * creation date.
	 */
	public List<Comment> findByContent(final Long contentID) {
		return new QueryEMContext<List<Comment>>() {
			@Override @SuppressWarnings("unchecked")
			public List<Comment> query(EntityManager em) {
				Query query = em.createQuery("Select from Comment c where c.contentID = :contentID and c.status = :status order by c.modified desc");
				query.setParameter("contentID", contentID);
				query.setParameter("status", CommentStatus.PUBLISHED);
				List<Comment> list = query.getResultList();
				return initialize(list);
			}
		}.result();
	}
	
	/**
	 * Returns {@link Comment}s by their given status.
	 */
	public Page<Comment> findByStatus(final CommentStatus status, final int start, final int end) {
		return new QueryEMContext<Page<Comment>>() {
			@Override @SuppressWarnings("unchecked")
			public Page<Comment> query(EntityManager em) {
				Query query = em.createQuery("Select from Comment c where c.status = :status order by c.modified desc");
				query.setParameter("status", status);
				query.setFirstResult(start);
				query.setMaxResults(end);
				List<Comment> list = query.getResultList();
				query = em.createQuery("Select count(c.id) from Comment c where c.status = :status");
				query.setParameter("status", status);
				return new Page<Comment>(initialize(list), (Integer) query.getSingleResult());
			}
		}.result();
	}
	
}